
/*-------------------------------------------------------------------------
 *
 * dict_simple.c
 *		简单字典：仅小写并检查停用词
 *
 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
 *
 *
 * IDENTIFICATION
 *	  src/backend/tsearch/dict_simple.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "commands/defrem.h"
#include "tsearch/ts_locale.h"
#include "tsearch/ts_utils.h"
#include "utils/builtins.h"


typedef struct
{
	StopList	stoplist;
	bool		accept;
} DictSimple;


Datum dsimple_init(PG_FUNCTION_ARGS)
{
	List	   *fc_dictoptions = (List *) PG_GETARG_POINTER(0);
	DictSimple *fc_d = (DictSimple *) palloc0(sizeof(DictSimple));
	bool		fc_stoploaded = false,
				fc_acceptloaded = false;
	ListCell   *fc_l;

	fc_d->accept = true;			/* 默认 */

	foreach(fc_l, fc_dictoptions)
	{
		DefElem    *fc_defel = (DefElem *) lfirst(fc_l);

		if (strcmp(fc_defel->defname, "stopwords") == 0)
		{
			if (fc_stoploaded)
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("multiple StopWords parameters")));
			readstoplist(defGetString(fc_defel), &fc_d->stoplist, lowerstr);
			fc_stoploaded = true;
		}
		else if (strcmp(fc_defel->defname, "accept") == 0)
		{
			if (fc_acceptloaded)
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("multiple Accept parameters")));
			fc_d->accept = defGetBoolean(fc_defel);
			fc_acceptloaded = true;
		}
		else
		{
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("unrecognized simple dictionary parameter: \"%s\"",
							fc_defel->defname)));
		}
	}

	PG_RETURN_POINTER(fc_d);
}

Datum dsimple_lexize(PG_FUNCTION_ARGS)
{
	DictSimple *fc_d = (DictSimple *) PG_GETARG_POINTER(0);
	char	   *fc_in = (char *) PG_GETARG_POINTER(1);
	int32		fc_len = PG_GETARG_INT32(2);
	char	   *fc_txt;
	TSLexeme   *fc_res;

	fc_txt = lowerstr_with_len(fc_in, fc_len);

	if (*fc_txt == '\0' || searchstoplist(&(fc_d->stoplist), fc_txt))
	{
		/* reject as stopword */
		pfree(fc_txt);
		fc_res = palloc0(sizeof(TSLexeme) * 2);
		PG_RETURN_POINTER(fc_res);
	}
	else if (fc_d->accept)
	{
		/* accept */
		fc_res = palloc0(sizeof(TSLexeme) * 2);
		fc_res[0].lexeme = fc_txt;
		PG_RETURN_POINTER(fc_res);
	}
	else
	{
		/* report as unrecognized */
		pfree(fc_txt);
		PG_RETURN_POINTER(NULL);
	}
}
